package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.GridLayoutManager
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.Const
import com.spark.common.ext.cancel
import com.spark.common.ext.wrapIO
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.trouble.R
import com.spark.trouble.model.ChkStdKeywordFilterModel
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.win_keyword.*

class KeywordFilterDF : DialogFragment() {
    private lateinit var keywordFileAdapter: KeywordFileAdapter
    private var dispose: Disposable? = null

    companion object {
        private var onFilterSelectListener: OnFilterSelectListener? = null
        fun newInstance(listener: OnFilterSelectListener?): KeywordFilterDF {
            val keywordSelectorDF = KeywordFilterDF()
            onFilterSelectListener = listener
            return keywordSelectorDF
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val window = dialog.window
        val rootView = inflater.inflate(R.layout.win_keyword, window.findViewById(android.R.id.content) as ViewGroup, false)
        window.apply {
            setGravity(Gravity.TOP)
            setLayout(-1, -2)
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        keywordFileAdapter = KeywordFileAdapter(R.layout.item_check_keyword_filter)
        recy_tags.apply {
            adapter = keywordFileAdapter
            layoutManager = GridLayoutManager(context, 4)
        }

        fetchTags()
        tv_reset.setOnClickListener {
            keywordFileAdapter.reset()
        }
        btn_affirm.setOnClickListener {
            val keyword = et_keyword.text.toString().trim()
            var result = keywordFileAdapter.summary()
            if (!keyword.isNullOrBlank()) {
                result = "$keyword,$result"
            }
            onFilterSelectListener?.onFilterChecked(result)
            dismiss()
        }
        iv_back.setOnClickListener { dismiss() }
        tv_title.text = "选择考核标准"
    }

    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
        dispose?.cancel()
    }

    @SuppressLint("CheckResult")
    fun fetchTags() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_chk_std_keyword}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, ChkStdKeywordFilterModel::class.java)?.apply {
                                if (code == "200") {
                                    keywordFileAdapter.addData(resultMaps)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }
}

interface OnFilterSelectListener {
    fun onFilterChecked(keyword: String)
}

class KeywordFileAdapter(layoutRes: Int) : BaseQuickAdapter<ChkStdKeywordFilterModel.ResultMap, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: ChkStdKeywordFilterModel.ResultMap?) {
        if (item == null) return
        helper?.apply {
            getView<TextView>(R.id.tv_tag).apply {
                text = item.name
                setTextColor(if (item.isChecked) mContext.resources.getColor(R.color.blue0092) else mContext.resources.getColor(R.color.color_d3dee9))
                setBackgroundResource(if (item.isChecked == true) R.drawable.bg_e8f6fe_round_rect_56aae2 else R.drawable.bg_d3dee9_round_rect_fff)
                setOnClickListener {
                    item.isChecked = !item.isChecked
                    notifyDataSetChanged()
                }
            }
        }
    }

    fun reset() {
        data.forEach {
            it.isChecked = false
        }
        notifyDataSetChanged()
    }

    fun summary(): String {
        var results: String = ""
        data.forEach {
            if (it.isChecked)
                results = "${it.clauseId},$results"
        }
        return results
    }

}